package com.eims.sls_app.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.eims.sls_app.service.UpdateService;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.view.ConfirmUpdateDialog;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import bls.juejin.cn.R;
import progressBar.MyProgressBar;

public class UpdateManager {
	private static final String TAG = "UpdateManager";
	private Context mContext;

	private ConfirmUpdateDialog dialog;// 提示框

	// titile标头
	private String updateMsg = "快点下载哦！";

	// 传入的下载地址
	private String apkUrl;

	private Dialog noticeDialog;

	private Dialog downloadDialog;
	/* 路径 */
	private static final String savePath = "/sdcard/updatedemo/";

	private static final String saveFileName = savePath
			+ "UpdateDemoRelease.apk";
	MyProgressBar myProgressBar;
	/* 进度 */
	private ProgressBar mProgress; // 进度

	private static final int DOWN_UPDATE = 1;

	private static final int DOWN_OVER = 2;

	private int progress;

	private Thread downLoadThread;

	private boolean interceptFlag = false;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_UPDATE:
				Log.i(TAG, "progress--  " + progress);
				myProgressBar.setPress(progress);
//				mProgress.setProgress(progress);
				break;
			case DOWN_OVER:
				myProgressBar.setPress(100);
//				mProgress.setProgress(progress);
				// 开始安装APK
//				downloadDialog.dismiss();
				installApk();
				break;
			default:
				break;
			}
		}
	};

	public UpdateManager(Context context, String url) {
		this.mContext = context;
		this.apkUrl = url;
	}

	public void checkUpdateInfo() {
		showNoticeDialog();
	}

	private void showNoticeDialog() {
		dialog = new ConfirmUpdateDialog(mContext, R.style.dialog,"http://888.qcai888.cn/clientsoft/shengji.png");
		dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
		dialog.setCancelable(false);
		AlertDialog.Builder builder = new Builder(mContext);
		// builder.setTitle("下载更新");
		dialog.show();
//		dialog.setDialogTitle("更新提示");
//		dialog.setDialogCancelText("下次再说");
//		dialog.setDialogConfirmText("下载");
//		dialog.setDialogContent("亲，有新版本可以下载啦！轻敲下载立即更新。");
		dialog.setDialogTitlebg("http://888.qcai888.cn/clientsoft/shengji.png");
		dialog.setDialogResultListener(new ConfirmUpdateDialog.DialogResultListener() {
			@Override
			public void getResult(int resultCode) {
				if (1 == resultCode) {// 确定
				 showDownloadDialog();//更新
					// 开启更新服务UpdateService
					// 这里为了把update更好模块化，可以传一些updateService依赖的值
					// 如布局ID，资源ID，动态获取的标题,这里以app_name为例
//					Intent updateIntent = new Intent(mContext,
//							UpdateService.class);
//					Bundle bundle=new Bundle();
//					bundle.putString("titleId", R.string.app_name);
//					updateIntent.putExtra("titleId", R.string.app_name);
//					updateIntent.putExtra("downloadURL",
//							App.appobject.getDownLoadUrl());
					Log.e(TAG, App.appobject.getDownLoadUrl());
//					mContext.startService(updateIntent);
				}
			}
		});
		// builder.setMessage(updateMsg);
		// builder.setPositiveButton("确定", new OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// dialog.dismiss();
		// showDownloadDialog();
		// }
		// });
		// builder.setNegativeButton("取消", new OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int which) {
		// MainActivity.genxinHandler.sendEmptyMessage(-1);
		// dialog.dismiss();
		// }
		// });
		// noticeDialog = builder.create();
		// noticeDialog.show();
	}

	private void showDownloadDialog() {
		myProgressBar = new MyProgressBar(mContext);
	
//		AlertDialog.Builder builder = new Builder(mContext);
//		builder.setTitle("下载中...");
//
//		final LayoutInflater inflater = LayoutInflater.from(mContext);
//		View v = inflater.inflate(R.layout.progress, null);
//		mProgress = (ProgressBar) v.findViewById(R.id.progress);
//
//		builder.setView(v);
//
//		builder.setNegativeButton("取消", new OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				// MainActivity.genxinHandler.sendEmptyMessage(-1);
//				dialog.dismiss();
//				downLoadThread.interrupt();
//				interceptFlag = true;
//				downLoadThread.interrupt();
//			}
//		});
//		downloadDialog = builder.create();
//		downloadDialog.setCanceledOnTouchOutside(false);
//		downloadDialog.show();
		myProgressBar.initDialog();
		downloadApk();
	}

	private Runnable mdownApkRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				Log.i(TAG, "更新地址------>" + apkUrl);
				URL url = new URL(apkUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setRequestProperty("Accept-Encoding", "identity");
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}
				String apkFile = saveFileName;
				File ApkFile = new File(apkFile);
				FileOutputStream fos = new FileOutputStream(ApkFile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 开始下载
					mHandler.sendEmptyMessage(DOWN_UPDATE);
					if (numread <= 0) {
						// 下载完成
						mHandler.sendEmptyMessage(DOWN_OVER);
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 读取完毕
				fos.close();
				is.close();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	};

	/**
	 * 下载apk
	 */

	private void downloadApk() {
		downLoadThread = new Thread(mdownApkRunnable);
		downLoadThread.start();

	}

	/**
	 * 安装װapk
	 */
	private void installApk() {
		File apkfile = new File(saveFileName);
		if (!apkfile.exists()) {
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		mContext.startActivity(i);
	}
}
